package com.example.Windturbine.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.Windturbine.Controller.ViewObject.Excel.MaterialExcel;
import com.example.Windturbine.Error.BusinessException;
import com.example.Windturbine.Error.EmBusinessError;
import com.example.Windturbine.Service.MaterialService;
import com.example.Windturbine.Service.Model.MaterialModel;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;

/**
 * @Author 丁永新
 * @Date 2021/12/17
 */
public class ExcelMaterialListener extends AnalysisEventListener<MaterialExcel> {

    MaterialService materialService;

    Integer userid;


    public ExcelMaterialListener(MaterialService materialService,  Integer userid) {
        this.materialService=materialService;
        this.userid=userid;
    }



    //存入数据库

    @SneakyThrows
    @Override
    public void invoke(MaterialExcel materialExcel, AnalysisContext analysisContext) {
        try{
            MaterialModel materialModel=convertFromExcel(materialExcel);
            materialModel.setLevel(userid);
            materialService.submitSingle(materialModel);
        }catch (Exception e){
            throw new BusinessException(EmBusinessError.UNKNOWN_ERROR,"Excel文件格式错误!");
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    private MaterialModel convertFromExcel(MaterialExcel materialExcel){
        MaterialModel materialModel=new MaterialModel();
        materialModel.setLevel(this.userid);
        BeanUtils.copyProperties(materialExcel,materialModel);
        return materialModel;
    }


}

